//
//  HJOAuthVc.swift
//  Weibo
//
//  Created by 韩佳 on 16/4/19.
//  Copyright © 2016年 ddg. All rights reserved.
//

import UIKit
import SVProgressHUD

//全局属性,其他类也可以访问
let WB_APP_KEY = "989667851"
let WB_APP_SECRET = "42df859090c9f0915557977e2f0351b8"
let WB_REDIRECT_URI = "http://www.baidu.com/"

class HJOAuthVc: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }
    override func loadView() {
        view = webView
        
        let URLString = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_APP_KEY)&redirect_uri=\(WB_REDIRECT_URI)"
        let url = NSURL(string: URLString)
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)

    }
    private lazy var webView: UIWebView = {
        let web = UIWebView()
        web.delegate = self
        return web
    }()
}

extension HJOAuthVc: UIWebViewDelegate {
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
//        print("\(request)")
        //获取url
        guard let url = request.URL else{
            return false
        }
        //判断url是否是我们想要的,以回调页开头
        if url.absoluteString.hasPrefix(WB_REDIRECT_URI) {
            //获取url中的参数
//            print(url.query)
            
            if let q = url.query where q.containsString("code=") {
                let code = q.substringFromIndex("code=".endIndex)
//                print(code)
                //
                HJUserAccountViewModel.shareAccount.loadAccessToken(code, finish: { (isSuccess) -> () in
                    if isSuccess{
                        //获取用户信息成功-->关闭当前页面-->切换控制器
                        self.dismissViewControllerAnimated(false, completion: { () -> Void in
                            NSNotificationCenter.defaultCenter().postNotificationName(HJChangeRootVCNotification, object: nil)
                        })
                        
                    }else{
                        //获取用户信息失败
                        print("获取用户信息失败")
                    }
                })
            }
            return false
        }
        
        return true
    }
//    //获取AccessToken
//    private func loadAccessToken(code: String){
//       let URLString = "https://api.weibo.com/oauth2/access_token"
//        let param = [
//            "client_id": WB_APP_KEY,
//            "client_secret": WB_APP_SECRET,
//            "grant_type":"authorization_code",
//            "code": code,
//            "redirect_uri":WB_REDIRECT_URI
//        ]
//            
//        
//        HJNetworkTools.shareTools.request(HJRequestMethod.Post, urlString: URLString, parameters: param) { (responseObject, error) -> () in
//            if error != nil {
//                print(error)
//                return
//            }
//            print("请求成功--\(responseObject)")
//            guard let dict = responseObject as? [String: AnyObject] else{
//                print("服务器数据类型错误")
//                return
//            }
//            //转模型
//            let account = HJUserAccount(dict: dict)
////            print(account)
//            //获取个人信息
//            self.loadUserInfo(account)
//        }
//    }
//    private func loadUserInfo(account: HJUserAccount){
//        let urlString = "https://api.weibo.com/2/users/show.json"
//        
//        let param = [
//            "access_token": account.access_token ?? "",
//            "uid": account.uid ?? ""
//        ]
//        
//        HJNetworkTools.shareTools.request(HJRequestMethod.Get, urlString: urlString, parameters: param) { (responseObject, error) -> () in
//            if error != nil {
//                SVProgressHUD.showErrorWithStatus("网络错误")
//            }
//            
//            guard let dict = responseObject as? [String: AnyObject] else{
//                print("服务器数据类型错误")
//                return
//            }
////            print(dict)
//            account.name = dict["name"] as? String
//            account.avatar_large = dict["avatar_large"] as? String
//            //保存用户信息
//            self.saveuserInfo(account)
//            
//        }
//
//    }
//    //归档
//    private func saveuserInfo(account: HJUserAccount){
//        let path = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.data")
//        print(path)
//        NSKeyedArchiver.archiveRootObject(account, toFile: path)
//    }
//    //解档
//    private func accountInSanbox()-> HJUserAccount?{
//        let path = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.data")
//        let result = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? HJUserAccount
//        return result
//    }
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}












